/*global $, sap*/
sap.designstudio.sdk.Component.subclass("com.justbi.data.Data", function() {

		// Properties
	  var component = null;
	  component = {
			  info : {		// component meta data
				  id : this.owner.sId,
				  name : "Just-BI Data",
				  designMode :  ( (window.sap && sap.zen && sap.zen.designmode) !== undefined) ? true : false,
				  self : this,
				  root : 'zen/mimes/sdk_include/com.justbi.data/res/',
				  buildFlag : true
			  },
			  ds_props : {	// properties specified in the contribution XML
				  configString : "",
				  dsData : null
			  }
	  };

	  
	  /* Generate getter and setters for the design studio properties (component.ds_props) */
	  for (var property in component.ds_props) {
		  if (component.ds_props.hasOwnProperty(property)) {
			  
			  // generate getter and setter functions
			  this[property] =
				  function(prop){
			      	return function(value) {
			      		if (value === undefined) {
			      			return component.ds_props[prop];
			      		}
			      		if (!( component.ds_props[prop] === value )  ){
			      			component.ds_props[prop] = value; 
			      			component.info.buildFlag = true;
			      		}
			      		return this;
			        };
			      }(property);
		  }
	  }
	  
	
	  /****************************************************************************
	   * 	DESIGN STUDIO EVENTS
	   ****************************************************************************/
	
	  /**
	   * Design Studio Event: Initialization
	   * This event triggered by Design Studio when the component is added to the
	   * canvas (or in Design Studio itself when moving the component around.
	   */
	  this.init = function() {
		  setToInit();
		  
		  // make sure that the width and height cannot be changed
		  this.$().width("50px");
		  this.$().height("50px");
	  };

  
	  /**
	   * Design Studio Event: AfterUpdate
	   * This event triggered by Design Studio when the properties of the component
	   * are updated.
	   */
	  this.afterUpdate = function() {
		  
		  if(component.ds_props.configString === ""){
			  return;
		  }
			  
		  // try to parse the string
		  var obj = null; 
		  try{
			  obj = JSON.parse(component.ds_props.configString);
		  }catch(error){
			  return;
		  }
		  
		  // the parsed object should be an array
		  if(obj.length === undefined || obj.length === 0){
			  return;
		  }
		  
		  // loop over the data models and set the data attribute on body level
		  for(var i=0;i<obj.length;i++){
			  
			  // check if the mandatory ID is specified
			  if(obj[i].id === undefined || obj[i].id === "" || obj[i].id === null){
				  continue;
			  }
			  
			  // check if the mandatory type is specified (and valid)
			  if(obj[i].type === undefined){
				  continue;
			  }else if(obj[i].type.toUpperCase() !== "STRING" && obj[i].type.toUpperCase() !== "URL" && obj[i].type.toUpperCase() !== "DESIGNSTUDIO" && obj[i].type.toUpperCase() !== "ODATA"){
				  continue;
			  }
			  
			  // Process the data setting
			  processData( obj[i] );
		  }
	  };
	
	  
	  /**
	   * Based on the settings, process the data
	   */
	  function processData( config ){
		  var newData = [];
		  
		  
		  // Data is delivered as STRING 
		  if(config.type.toUpperCase() === "STRING" && config.data !== undefined && config.data.length !== undefined && config.data.length > 0){
			  
			  // check type (JSON or CSV)
			  if(config.format !== undefined && config.format !== null && config.format !== ""){
				
				  // convert CSV to JSON
				  if(config.format.toUpperCase() === 'CSV'){
					  try{
						  newData = config.data.toObjects();  
					  }catch(error){
						  return;
					  }
				  }
				  
				  // move the data to JSON format
				  if(config.format.toUpperCase() === "JSON"){
					  newData = config.data;
				  }
			  }
		  }
		  
		  // Data is delivered as Design Studio Datasource (DESIGNSTUDIO)
		  if(config.type.toUpperCase() === "DESIGNSTUDIO"){
			  
			  // check if data is provided
			  if(component.ds_props.dsData !== undefined && component.ds_props.dsData !== null && component.ds_props.dsData !== "" && component.ds_props.dsData.tuples !== undefined && component.ds_props.dsData.tuples !== null && component.ds_props.dsData.tuples.length > 0){
				  
				  // looping over the rows
				  for(var rowIndex=0;rowIndex<component.ds_props.dsData.tuples.length;rowIndex++){
					 var obj = {};
					 var skipRecord = false;
					 
					 // looping over the dimensions
					 for(var colIndex=0;colIndex<component.ds_props.dsData.tuples[0].length;colIndex++){
						 var member = component.ds_props.dsData.dimensions[colIndex].members[component.ds_props.dsData.tuples[rowIndex][colIndex]];
						 if(member.type !== undefined && member.type === "RESULT"){
							 skipRecord = true;
							 break;;
						 }else{
							 obj[component.ds_props.dsData.dimensions[colIndex].key+"_KEY"] = member.key;
							 obj[component.ds_props.dsData.dimensions[colIndex].key+"_TEXT"] = member.text;
						 }
					 }
					 
					 // add the measure
					 if(!skipRecord){
						 obj["VALUE"] = component.ds_props.dsData.data[rowIndex];
						 newData.push(obj);
					 }
					 
				  }
			  }
		  }
		  
		  // Data is delivered as oData service
		  if(config.type.toUpperCase() === "ODATA"){
			  
			  // check if the URL is provided
			  
			  var query = "http://developersmackdown.com/services/odata/Shows" //root uri
			      + "?$select=ShowId,Title,PublicUri" //reduce the payload to what we need
			      + "&$orderby=ShowId%20desc" //order by and sort by the latest shows
			      + "&$top=5" //take the top 5
			      + "&$format=json" //give me json
			      + "&$callback=callback"; //this is my callback
			             
			  query = "http://services.odata.org/V3/Northwind/Northwind.svc/Customers?$format=json";
			  
			    $.ajax({
			      dataType: 'json',
			      url: query,
			      jsonpCallback: 'callback',
			      success: callback
			    });
			 
			     function callback(result) {
			       //var shows = result.d;
			       //$('#dsListTemplate').tmpl(shows).appendTo('#ds_shows');
			       console.log(result);
			     }
			 
			  
		  }
		  
		  
		  // retrieve the already loaded data
  		  var customDataObject = ( $("body").data("customData") !== undefined ) ?  $("body").data("customData") :  {};
  		  
  		  // check if the data has been changed
  		  if(JSON.stringify(customDataObject[config.id]) !== JSON.stringify(newData)){
  			customDataObject[config.id] = newData;
  	  		
    		  // update the data attribute
    		  $("body").data("customData", customDataObject);  
  		  
    		// acknowledge other components about the data update
    		  $.event.trigger('dataTrigger'+config.id);
  		  }
  		  
	  }
	  
	  
	  
	  
	  /**
	   * Design Studio Event: componentDeleted
	   * This event triggered by Design Studio when the component is removed from
	   * the canvas
	   */
	  this.componentDeleted = function() {
	    
	  };
	  
	  
	  function setToInit(){
		  if(component.info.designMode){
		      $("#" + component.info.id ).html('<img alt="" src="" />');
		  }else{
			  $("#" + component.info.id ).html('');
		  }
	  }
  
});